package com.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.util.PropertiesHelper;
import com.demo.util.Upload;
import com.demo.vo.EventVO;
import com.demo.vo.ResultVO;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import com.jfinal.kit.StringKit;

@ClearInterceptor(ClearLayer.ALL)
public class CommonNewController extends Controller {
	private static final int String = 0;

	public void index() {
		String code = getPara("code");

		String openid = "";
		if (StringKit.notBlank(getCookie("openid"))) {
		      openid = getCookie("openid");
		    }
		    else if (StringKit.notBlank(code)) {
		      openid = getopendid(code);
		      setCookie("openid", openid, 864000);
		    }
		    else
		    {
		      redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx665766efbb169f39&redirect_uri=http://shmiandi.cn/wzcx&response_type=code&scope=snsapi_base&state=123#qgjtw_redirect");
		      return;
		    }
		if (StringKit.notBlank(getPara("openid"))) {
			openid = getPara("openid");
			System.out.println("---------------------------getPara get openid"
					+ openid);

		}
//		 if (!StringKit.notBlank(openid)) {
//    	System.out.println("sssss");
//        renderError(404, "/404error.html");
//        return;
//      }
		String args = getPara("args");
		List<Record> carlist = new ArrayList<Record>();
		List<Record> car = new ArrayList<Record>();
		if (StringKit.notBlank(openid)) {
			car = Db.find("select  *  from t_car where openid='" + openid + "'");
		}

		if (StringKit.notBlank(args)) {
			carlist = Db.find("select * from t_car where id=" + args + "");
		}

		List<Record> _list = new ArrayList<Record>();
		List<Record> _lists = new ArrayList<Record>();
		_list = CacheKit.get("province", "province");
		if (_list == null) {
			_list = Db.find("select * from t_city order by id");
			CacheKit.put("province", "province", _list);
		}
		_lists = CacheKit.get("city", "city");
		if (_lists == null) {
			_lists = Db.find("select  * from t_xian order by id");
			CacheKit.put("city", "city", _lists);
		}
		System.out.println("---------------------" + car.size());
		// String action=getPara("action");
		// if(StringKit.notBlank(action) && action.equals("edit")){
		//
		// }
		if (StringKit.notBlank(getPara("openid"))) {
			setAttr("objectlist",
					Car.dao.find("select * from t_car where openid=? ", openid));
			setAttr("province", _list);
			setAttr("openid", openid);
			setAttr("city", _lists);
			setAttr("carlist", carlist);
			setAttr("args", args);
			renderFreeMarker("/vehicle-action.html");
		} else {
			if (car.size() > 0) {
				setAttr("openid", openid);
				setAttr("objectlist", Car.dao.find(
						"select * from t_car where openid=? ", openid));
				List<Record> list = Db
						.find(" SELECT SUM( a.fen ) AS unhandled_violation_point, "
								+ " SUM( a.money ) AS unhandled_violation_fine, COUNT( * ) AS unhandled_count, UPPER( a.hphm) AS vehicle_id"
								+ " FROM t_eventlist a, t_car b   WHERE a.hphm = b.hphm AND b.openid ='"
								+ openid + "'  GROUP BY a.hphm");
				if (StringKit.notBlank(getPara("add"))) {
					if (getPara("add").endsWith("add")) {
						setAttr("province", _list);
						setAttr("openid", openid);
						setAttr("city", _lists);
						setAttr("carlist", carlist);
						renderFreeMarker("/vehicle-action.html");
					}
				} else {
					setAttr("openid", openid);
					setAttr("fenz", list);
					renderFreeMarker("/vehicle-list.html");
				}
			} else {
				setAttr("province", _list);
				setAttr("openid", openid);
				setAttr("city", _lists);
				setAttr("carlist", carlist);
				setAttr("args", args);
				renderFreeMarker("/vehicle-action.html");
			}
		}
	}

	public void violations() {
		String id = getPara("args");
		List<Record> carlist = Db.find("select * from t_car where id =?", id);
		setAttr("carlist", carlist);
		setAttr("args", id);
		renderFreeMarker("/vehicle-violations.html");
	}

	public void queryList() {

		String args = getPara("args");
		String city = "";// String 是 城市代码 *
		String hphm = "";// String 是 号牌号码 完整7位 *
		String hpzl = "02";// String 是 号牌种类编号 (参考号牌种类接口)* 02小型车
		String engineno = "";// String 否 发动机号 (根据城市接口中的参数填写)
		String classno = "";// String 否 车架号 (根据城市接口中的参数填写)
		String registno = "";// String 否 车辆登记证书号 (根据城市接口中的参数填写)
		// 当天日期
		String cxrq = "";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		cxrq = sdf.format(date);

		List<Record> carlist = Db.find("select * from t_car where id =?", args);
		if (carlist.size() > 0) {
			hphm = carlist.get(0).getStr("hphm");
			city = carlist.get(0).getStr("city_code");
			engineno = carlist.get(0).getStr("engine_num");
			classno = carlist.get(0).getStr("body_num");
			registno = carlist.get(0).getStr("license_number");
		}

		String rq = "";

		// 获取最后一条记录
		List<Record> datelist = Db
				.find("select * from t_querylog where hphm ='" + hphm
						+ "' order by id desc ");
		List<Record> datlist = Db
				.find("select * from t_eventlist  where hphm ='" + hphm
						+ "' order by id desc ");

		int j = 0;
		System.out.println("======datelist.size()" + datelist.size());
		if (datelist.size() > 0) {
			rq = datelist.get(0).get("cxrq").toString();
			// 日期比较
			j = cutTwoDateToDay(rq, cxrq);
		}
		System.out.println("===============" + city);
		System.out.println("=======j========" + j);

		// 如果log大于0而且大于查询天数 就查接口 车辆违章记录为0而且 查询记录大于0 也查询接口

		if ((datelist.size() > 0 && j > UpdateRecordUtils.cardate)
				|| (datlist.size() == 0 && datelist.size() > 0)
				|| (datlist.size() == 0 && datelist.size() == 0)) {
			try {
				List<Record> cityList = Db
                        .find("SELECT DISTINCT(city_name) as city FROM `t_xian` WHERE abbr='" + hphm.substring(0, 1) + "'");
				for (Record record : cityList) {//遍历查找
                    String queryStr = "cityName=" + java.net.URLEncoder.encode(java.lang.String.valueOf(record.get("city")), "utf-8") + "&plateNumber="
                            + java.net.URLEncoder.encode(hphm, "utf-8") + "&hpzl="
                            + hpzl + "&engineNumber=" + engineno + "&vehicleIdNumber=" + classno
                            + "&key=" + UpdateRecordUtils.carkey;
                    //0 不推送
					UpdateRecordUtils.updateRecord(queryStr, hphm, cxrq,"0","");
                }
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

//		renderText(callback +"("+obj.toJSONString()+")");
		resultJson2(hphm, city);
	}


	//新建的查询违章数据方法
	public void getResJson(){
		//从本机数据库进行查询
		String platform_id=getPara("platform_id");//平台号
		String carid=getPara("carid");
		String cityid = getPara("cityid");//城市ID
		String cip=getPara("cip");//来源ip
		String platenum=getPara("platenum");//车牌号
		String enginenumber=getPara("enginenumber");//发动机号
		String framenumber=getPara("framenumber");//车架号
		String Lng = getPara("Lng");//经度
		String DLat = getPara("DLat");//纬度
		Map<String, String> map=new HashMap<String, String>();
		//根据车辆ID获取车辆的详细信息

		//组装向服务器发送的数据
		map.put("platform_id", platform_id);
		map.put("cityid", cityid);
		map.put("cip", cip);
		map.put("platenum", platenum);
		map.put("enginenumber", enginenumber);
		map.put("framenumber", framenumber);
		map.put("Lng", Lng);
		map.put("DLat", DLat);


		//向服务器请求查询结果
		String string = HttpKit.post("http://open.wz.qichecdn.com/violaton/GetViolation", map,"");
		//如果数据库中有该违章信息，直接返回结果给用户
		//如果数据库中没有该违章信息，保存，并返回JSON给用户
	}
	//原有的查询违章数据方法
	public void resultListJson() throws UnsupportedEncodingException {
		String args = getPara("args");//车辆ID
		String city = "";// String 是 城市代码 *
		String hphm = "";// String 是 号牌号码 完整7位 *
		String hpzl = "02";// String 是 号牌种类编号 (参考号牌种类接口)* 02小型车
		String engineno = "";// String 否 发动机号 (根据城市接口中的参数填写)
		String classno = "";// String 否 车架号 (根据城市接口中的参数填写)
//		String registno = "";// String 否 车辆登记证书号 (根据城市接口中的参数填写)
		// 当天日期
		String cxrq = "";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		cxrq = sdf.format(date);

		List<Record> carlist = Db.find("select * from t_car where id =?", args);
		if (carlist.size() > 0) {
			hphm = carlist.get(0).getStr("hphm");
			city = carlist.get(0).getStr("city_code");
			engineno = carlist.get(0).getStr("engine_num");
			classno = carlist.get(0).getStr("body_num");
//			registno = carlist.get(0).getStr("license_number");
		}

		String rq = "";

		// 获取最后一条记录
		List<Record> datelist = Db
				.find("select * from t_querylog where hphm ='" + hphm
						+ "' order by id desc ");
		List<Record> datlist = Db
				.find("select * from t_eventlist  where hphm ='" + hphm
						+ "' order by id desc ");

		int j = 0;
		System.out.println("======datelist.size()" + datelist.size());
		if (datelist.size() > 0) {
			rq = datelist.get(0).get("cxrq").toString();
			// 日期比较
			j = cutTwoDateToDay(rq, cxrq);
		}
		System.out.println("===============" + city);
		System.out.println("=======j========" + j);

		// 如果log大于0而且大于查询天数 就查接口 车辆违章记录为0而且 查询记录大于0 也查询接口

		if ((datelist.size() > 0 && j > UpdateRecordUtils.cardate)
				|| (datlist.size() == 0 && datelist.size() > 0)
				|| (datlist.size() == 0 && datelist.size() == 0)) {


			List<Record> cityList = Db
					.find("SELECT DISTINCT(city_name) as city FROM `t_xian` WHERE abbr='"+hphm.substring(0,1)+"'");
			for (Record record : cityList) {//遍历查找
				System.out.println(">>>select " + record.get("city"));
				String queryStr = "cityName=" +java.net.URLEncoder.encode(java.lang.String.valueOf(record.get("city")), "utf-8")+ "&plateNumber="
						+ java.net.URLEncoder.encode(hphm, "utf-8") + "&hpzl="
						+ hpzl + "&engineNumber=" + engineno + "&vehicleIdNumber=" + classno
						+ "&key=" +UpdateRecordUtils.carkey;
				//0 不推送
				UpdateRecordUtils.updateRecord(queryStr, hphm, cxrq,"0","");
			}
		}

		resultJson(hphm, city);

	}



	public void vehicle_list() {

		String openid = getPara("openid");
		setAttr("objectlist",
				Car.dao.find("select * from t_car where openid=?", openid));
		setAttr("openid", openid);
		renderFreeMarker("/vehicle-list.html");
	}

	public void listJson() {
		String openid = getPara("openid");
		ArrayList List = new ArrayList();
		List<Record> list = Db
				.find("  select sum(fen) as unhandled_violation_point,sum(money)   as unhandled_violation_fine ,"
						+ " count(*)  as  unhandled_count,"
						+ "hphm as vehicle_id from t_eventlist where hphm in (select hphm from t_car where openid = '"
						+ openid + "')  group by hphm");
		if (list.size() > 0) {
			for (Record n : list) {
				List.add(n);
			}
		}

		List<Record> car = new ArrayList<Record>();
		if (StringKit.notBlank(openid)) {
			car = Db.find("select  '0' as unhandled_violation_point  , '0'  as  unhandled_violation_fine ,'0' as unhandled_count,"
					+ "hphm as vehicle_id    from t_car where  hphm not in (select hphm from  t_eventlist  group by hphm) and openid='"
					+ openid + "'");
			for (Record n : car) {
				List.add(n);
			}
		}

		renderJson(List);
		// render(new JsonRender(List).forIE());

	}

	public void queryjson() {
		String openid = getPara("openid");
		String action = getPara("action");
		String license_num = getPara("license_num");
		String license_number = getPara("license_number");
		String body_num = getPara("body_num");
		String engine_num = getPara("engine_num");
//		String city_name = getPara("city_name");
		String city_name = "";
//		String city_code = getPara("city_code");
		String city_code = "";
		System.out.println("=================" + openid);
		Car temp = Car.dao.findFirst("select * from t_car where hphm =  '"
				+ license_num + "'   and openid  = '" + openid + "'");
		System.out.println("=================" + temp);

		String args = getPara("args");
		if (action.equals("add")) {
			if (temp == null) {
				Car car = new Car();
				car.set("hphm", license_num)
						.set("license_number", license_number)
						.set("body_num", body_num)
						.set("engine_num", engine_num)
						.set("city_name", city_name)
						.set("city_code", city_code);
				car.set("openid", openid);// 替换openid
				boolean flag = car.save();
				if (flag) {
					String content = "{\"msg\":\"ok\",\"id\":\"args="
							+ car.getInt("id") + "\"}";
					JSONObject jsonText = (JSONObject) JSON.parse(content);
					renderJson(jsonText);
					// render(new JsonRender(jsonText).forIE());

				}
			} else {
				String content = "{\"msg\":\"ok\",\"id\":\"args="
						+ temp.get("id").toString() + "\"}";
				System.out.println("--------------" + content);
				JSONObject jsonText = (JSONObject) JSON.parse(content);
				renderJson(jsonText);

				// render(new JsonRender(jsonText).forIE());
			}
		} else {
			Car car = new Car();
			car.set("hphm", license_num).set("license_number", license_number)
					.set("body_num", body_num).set("engine_num", engine_num)
					.set("city_name", city_name).set("city_code", city_code)
					.set("id", Integer.parseInt(args));// 替换openid
			boolean flag = car.update();
			if (flag) {
				String content = "{\"msg\":\"ok\",\"id\":\"args=" + args
						+ "\"}";
				JSONObject jsonText = (JSONObject) JSON.parse(content);
				renderJson(jsonText);
			} else {
				String content = "{\"msg\":\"no\",\"id\":\"args=" + args
						+ "\"}";
				JSONObject jsonText = (JSONObject) JSON.parse(content);
				renderJson(jsonText);

				// render(new JsonRender(jsonText).forIE());
			}
		}
	}

	public void delete() {
		String action = getPara("action", "");
		if (action.equals("del")) {
			String args = getPara("args");
			boolean flag = Car.dao.deleteById(args);
			if (flag) {
				String content = "{\"msg\":\"ok\"}";
				JSONObject jsonText = (JSONObject) JSON.parse(content);
				renderJson(jsonText);
				// render(new JsonRender(jsonText).forIE());

				return;
			}

		}
	}

	public static void main(String[] args) {
		String a = "2014-12-28 00:00:00";
		String b = "2015-01-01 00:00:00";
		int c = cutTwoDateToDay(a, b);
		System.out.println("===================" + c);
	}

	/**
	 * 计算两个日期之间的差距天数
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static int cutTwoDateToDay(String a, String b) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		int theday = 0;
		try {
			Date beginDate = format.parse(a);
			Date endDate = format.parse(b);

			calendar.setTime(beginDate);
			long begin = calendar.getTimeInMillis();
			calendar.setTime(endDate);
			long end = calendar.getTimeInMillis();

			theday = (int) ((end - begin) / (86400000));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return theday;
	}

	@SuppressWarnings("unchecked")
	public void resultJson2(String hphm, String city) {
		int total_fine = 0;// 总金额
		int total_point = 0;// 总分值
		int total_count = 0;// 总条数
		String data_timestamp = ""; // 查询时间戳//
		int page_size = 0;
		String stat = "";
		String message = null;
		List<Record> list = Db
				.find("select  id as vehicle_id,area as violation_address ,act as violation_type ,"
						+ "fen as violation_points ,money as violation_fine ,"
						+ " handled as violation_status_text , longitude as  violation_longitude "
						+ ", latitude as  violation_latitude  ,code  as violation_count ,  UNIX_TIMESTAMP(date) as violation_time "
						+ " from  t_eventlist where hphm ='"
						+ hphm
						+ "'    order by date desc");
		for (Record n : list) {
			total_fine += Integer.parseInt(n.get("violation_fine").toString());
			total_point += Integer.parseInt(n.get("violation_points")
					.toString());
		}
		HashMap map = new HashMap();
		if (list.size() > 0) {
			map.put("stat", "ok");
			map.put("data", list);
			map.put("total_count", list.size());
			map.put("message", null);
			map.put("total_fine", total_fine);
			map.put("total_point", total_point);
			map.put("page_size", "10");
		} else {
			map.put("stat", "no");
			map.put("data", list);
			map.put("total_count", list.size());
			map.put("message", " 未查询到违章记录 请保持良好驾驶习惯");
			map.put("total_fine", total_fine);
			map.put("total_point", total_point);
			map.put("page_size", "0");
		}
		JSONObject obj =new JSONObject();
		obj.putAll(map);
		final String callback = getPara("callback");
		renderText(callback +"("+obj.toJSONString()+")");
		// render(new JsonRender(map).forIE());
	}
	
	public void resultJson(String hphm, String city) {
		int total_fine = 0;// 总金额
		int total_point = 0;// 总分值
		int total_count = 0;// 总条数
		String data_timestamp = ""; // 查询时间戳//
		int page_size = 0;
		String stat = "";
		String message = null;
		List<Record> list = Db
				.find("select  id as vehicle_id,area as violation_address ,act as violation_type ,"
						+ "fen as violation_points ,money as violation_fine ,"
						+ " handled as violation_status_text , longitude as  violation_longitude "
						+ ", latitude as  violation_latitude  ,code  as violation_count ,  UNIX_TIMESTAMP(date) as violation_time "
						+ " from  t_eventlist where hphm ='"
						+ hphm
						+ "'    order by date desc");
		for (Record n : list) {
			total_fine += Integer.parseInt(n.get("violation_fine").toString());
			total_point += Integer.parseInt(n.get("violation_points")
					.toString());
		}
		HashMap map = new HashMap();
		if (list.size() > 0) {
			map.put("stat", "ok");
			map.put("data", list);
			map.put("total_count", list.size());
			map.put("message", null);
			map.put("total_fine", total_fine);
			map.put("total_point", total_point);
			map.put("page_size", "10");
		} else {
			map.put("stat", "no");
			map.put("data", list);
			map.put("total_count", list.size());
			map.put("message", " 未查询到违章记录 请保持良好驾驶习惯");
			map.put("total_fine", total_fine);
			map.put("total_point", total_point);
			map.put("page_size", "0");
		}
		renderJson(map);
		// render(new JsonRender(map).forIE());

	}

	public String getopendid(String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code";
		url = url.replace("AppId", UpdateRecordUtils.AppId).replace("AppSecret", UpdateRecordUtils.AppSecret)
				.replace("CODE", code);
		String jsonResult = HttpKit.get(url);
		JSONObject jsonTexts = (JSONObject) JSON.parse(jsonResult);
		String openid = "";
		if (StringKit.notNull(jsonTexts.get("openid"))) {
			openid = jsonTexts.get("openid").toString();
		}
		System.out.println("===============" + openid);

		return openid;
	}

}
